<template>
  <div>
    <div :title="tagFormulaText" class="default-text ellipsisOne" @click="openDialog">{{ tagFormulaText }}</div>
    <el-drawer
      :visible.sync="dialogFormVisible"
      :with-header="false"
      :before-close="closeDialog"
      :append-to-body="true"
      size="800px">
      <div class="drawer-main">
        <div class="title-container">
          <div><Title title="设置公式" style="margin-bottom: 16px;" /></div>
          <div v-if="elementOptions && elementOptions.modeType === 1" class="tip">运算符号使用  +  -  *  /</div>
        </div>
        <div v-if="elementOptions" class="scroll-main main">
          <OverviewFormula
            v-if="!elementOptions.modeType"
            v-model="elementOptions.formulaOrigin"
            :tags-options="numberFieldList"
            :math-tag="mathTag"
            :form-options-list="formOptions.list"
            :current-element="selectWidget"
            value-key="key"
            quote-label-name="引用字段" >
            <el-form-item label="数据筛选" style="margin-right: 16px;margin-bottom: 15px;">
              <FormulaFilter v-model="elementOptions.filterList" :formula-origin="elementOptions.formulaOrigin" />
            </el-form-item>
          </OverviewFormula>
          <FormulaEdit v-else ref="hightModeFormulaRef" :form-options="formOptions" :field-list="fieldList" />
        </div>
        <div v-if="elementOptions" class="btn">
          <el-button type="primary" size="small" @click="toSubmit()">保存</el-button>
          <el-button type="info" size="small" class="cancel-btn-style" @click="closeDialog">取消</el-button>
          <div class="button-text" @click="switchMode">{{ !elementOptions.modeType?'进入高级模式':'退出高级模式' }}</div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Title from '@/components/Title';
import OverviewFormula from './overviewFormula';
import FormulaEdit from './formulaEdit';
import FormulaFilter from './formulaFilter';
import { getConfigData } from '@/components/Common/relatedProcess/data';
import { forEachFormOptions, isNumberType } from '@/utils/formMakeUtils.js';
import { getFormulaVariable } from '@/views/legal/process/components/formMake/utils/index.js';
import { mapState } from 'vuex';
export default {
  components: { OverviewFormula, Title, FormulaFilter, FormulaEdit },
  model: {
    prop: 'selectWidget',
    event: 'changeData'
  },
  props: {
    selectWidget: {
      type: Object,
      default: () => ({})
    },
    keyToFormula: {
      type: Object,
      default: () => ({})
    },
    formOptions: {
      type: Object,
      default: () => {
        return {
          list: []
        };
      }
    }
  },
  data() {
    return {
      mathTag: [
        { name: 'x', key: '*', type: 'math' },
        { name: '÷', key: '/', type: 'math' },
        { name: '+', key: '+', type: 'math' },
        { name: '-', key: '-', type: 'math' },
        { name: '(', key: '(', type: 'math' },
        { name: ')', key: ')', type: 'math' },
        { name: '平均', key: 'average', type: 'math' },
        { name: '求和', key: 'sum', type: 'math' },
        { name: '计数', key: 'count', type: 'math' }
      ],
      dialogFormVisible: false,
      tableHeight: '',
      elementOptions: null,
      fieldList: [],
      numberFieldList: []
    };
  },
  computed: {
    ...mapState({
      'widgetTypes': state => state.formMake.widgetTypes
    }),
    numberField() {
      if (this.widgetTypes && this.widgetTypes.number) {
        return [...this.widgetTypes.number, ...this.linkFormNumberField];
      }
      return [];
    },
    linkFormNumberField() {
      // 关联表单中的数值型字段
      // 只有开启 “将数值型字段设为统计字段” 时才会有
      let ans = [];
      const linkForm = this.widgetTypes.linkForm;
      if (!linkForm) return [];
      linkForm.forEach(i => {
        if (i.options.isStatistics && i.options.statistics.length) {
          const statisticsField = i.subform.filter(j => {
            if (j.type !== 'statistics' && i.options.statistics.includes(j.key)) {
              j._parentName = i.name;
              return true;
            }
            return false;
          });
          if (statisticsField) ans = ans.concat(statisticsField);
        }
      });
      return ans;
    },
    tagFormulaText() {
      const selectWidget = this.selectWidget;
      if (!selectWidget.options.modeType) {
        return this.getNormalLabels() || '点击设置公式';
      } else if (selectWidget.options.formulaString) {
        return this.getHighLabels();
      }
      return '点击设置公式';
    }
  },
  mounted() {
    this.update();
  },
  methods: {
    update() {
      const formulaOrigin = this.selectWidget.options.formulaOrigin;
      if (formulaOrigin && formulaOrigin.length) {
        const oldLen = formulaOrigin.length;
        this.selectWidget.options.formulaOrigin = formulaOrigin.filter(i => {
          if (i.type === 'math' || i.type === 'number') return true;
          const hasField = this.numberField.some(j => j.key === i.key);
          return hasField;
        });
        if (oldLen !== this.selectWidget.options.formulaOrigin.length) {
          this.setData(this.selectWidget.options);
        }
      }
    },
    toSubmit() {
      this.setData(this.elementOptions);
      this.closeDialog();
    },
    setData(elementOptions) {
      // 获取公式相关数据
      const el = _.cloneDeep(this.selectWidget);
      if (!elementOptions.modeType) {
        const { formulaOrigin, tagFormula } = getFormulaVariable(elementOptions, this.selectWidget, this.keyToFormula);
        this.$set(this.selectWidget.options, 'formulaOrigin', formulaOrigin || []);
        this.$set(this.selectWidget.options, 'tagFormula', tagFormula || '');
        this.$set(this.selectWidget.options, 'filterList', elementOptions.filterList || []);
        this.$store.dispatch('addWidget', { type: 'number', widget: el });
      } else {
        const formulaString = this.$refs.hightModeFormulaRef ? this.$refs.hightModeFormulaRef.formulaString : '';
        this.$set(this.selectWidget.options, 'formulaString', formulaString || '');
        this.$store.dispatch('removeWidget', { type: 'number', widget: el });
      }
      this.$set(this.selectWidget.options, 'modeType', elementOptions.modeType || 0);
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.elementOptions = null;
    },
    openDialog() {
      this.elementOptions = _.cloneDeep(this.selectWidget.options);
      const clientHeight = window.innerHeight;
      this.tableHeight = (clientHeight * 3) / 5;
      this.dialogFormVisible = true;
      this.getAllKeywords();
      this.$nextTick(() => {
        if (this.elementOptions.modeType === 1) this.$refs.hightModeFormulaRef.setDefault(this.elementOptions.formulaString);
      });
    },
    // 排除当前字段 和 重复字段
    handelData(list, key) {
      const hasKey = [];
      return list.filter(i => {
        const ans = i.key !== key && !hasKey.includes(i.key);
        if (ans) hasKey.push(i.key);
        return ans;
      });
    },
    linkFormConfigData(linkFormElement) {
      if (!linkFormElement || !linkFormElement.options || !linkFormElement.options.remoteParams) return null;
      const type = linkFormElement.options.remoteParams.type;
      return getConfigData(type);
    },
    switchMode() {
      const modeType = this.elementOptions.modeType;
      this.$set(this.elementOptions, 'modeType', !modeType ? 1 : 0);
      this.$nextTick(() => {
        if (this.elementOptions.modeType === 1) this.$refs.hightModeFormulaRef.setDefault(this.elementOptions.formulaString);
      });
    },
    getAllKeywords() {
      const fieldList = [];
      const numberFieldList = [];
      forEachFormOptions(this.formOptions.list, (item, subformKey, parentSubform) => {
        const exclude = [
          'grid', 'titleExplain', 'linkForm', 'subform', 'title',
          'workflowId', 'associatedApproval', 'richEditor',
          'upAttachment'
        ];
        if (item.key !== this.selectWidget.key && !exclude.includes(item.type)) {
          const cloneItem = _.cloneDeep(item);
          if (parentSubform) {
            cloneItem.name = `${parentSubform.name}.${cloneItem.name}`;
          }
          fieldList.push(cloneItem);
          if (isNumberType(item)) {
            numberFieldList.push(_.cloneDeep(cloneItem));
          }
        }
        if (item.type === 'linkForm' && item.options.isStatistics && item.options.statistics) {
          // 关联表单统计字段
          item.options.statistics.forEach(st => {
            const linkItem = item.subform.find(subEl => subEl.key === st);
            const cloneItem = _.cloneDeep(linkItem);
            const numberCloneItem = _.cloneDeep(linkItem);
            cloneItem.key = `${item.key}_${cloneItem.key}`;
            cloneItem.type = 'statistics';
            cloneItem.name = `${item.name}.${cloneItem.name}`;
            fieldList.push(cloneItem);

            numberCloneItem.type = 'statistics';
            numberCloneItem.name = `${item.name}.${numberCloneItem.name}`;
            numberFieldList.push(numberCloneItem);
          });
        }
      });
      this.fieldList = fieldList;
      this.numberFieldList = numberFieldList;
    },
    // 获取普通模式的标签
    getNormalLabels() {
      const selectWidget = this.selectWidget;
      const formOptionsList = this.formOptions.list;
      const linkFormNumberField = this.linkFormNumberField;
      let tagFormulaText = '';
      if (selectWidget.options.formulaOrigin) {
        selectWidget.options.formulaOrigin.forEach(j => {
          let name = j.name;
          const key = j.key;
          if (j.type !== 'math' && j.type !== 'number') {
            const link = linkFormNumberField.find(i => i.key === key);
            if (link) {
              name = `${link._parentName}.${link.name}`;
            } else {
              forEachFormOptions(formOptionsList, (item, k, parentSubform) => {
                if (item.key === key) {
                  name = item.name;
                  if (item.isSubTable && item.linkFormKey && parentSubform) {
                    name = `${parentSubform.name}.${item.name}`;
                  }
                }
              });
            }
            j.name = name;
          }
          tagFormulaText = tagFormulaText + name;
        });
      }
      return tagFormulaText;
    },
    // 获取高级模式的标签
    getHighLabels() {
      const widget = /\$_widget_(.+?)_end\$/g;
      const formOptionsList = this.formOptions.list;
      const selectWidget = this.selectWidget;
      return selectWidget.options.formulaString.replace(widget, function(math, key) {
        let name = math;
        forEachFormOptions(formOptionsList, (item, k, parentSubform) => {
          if (item.key === key) {
            name = item.name;
            if (parentSubform) {
              name = `${parentSubform.name}.${item.name}`;
            }
          }
          if (item.type === 'linkForm') {
            item.subform.forEach(subItem => {
              if (key === `${item.key}_${subItem.key}`) {
                name = `${item.name}.${subItem.name}`;
              }
            });
          }
        });
        return name;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.drawer-main {
  padding: 24px;
}
.scroll-main {
  max-height: calc(100vh - 40px - 100px);
  @include scrollBar();
}
.default-text {
  color: #406eff;
  font-size: 14px;
  cursor: pointer;
}
.btn {
  display: flex;
  align-items: center;
  margin-top: 20px;
  .button-text {
    margin-left: 10px;
  }
}
.title-container {
  display: flex;
  .tip {
    font-size: 12px;
    color: #666;
    margin-left: 10px;
  }
}
</style>
